﻿using AuthCenter.Common;
using AuthCenter.Intertructrue;
using AuthCenter.Intertructrue.Implement;
using AuthCenter.Intertructrue.Interface;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Reflection;
using System.Text;

namespace AuthCenter.API.Extensions
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 注册中介者
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection MediatR(this IServiceCollection services)
        {
            services.AddMediatR(cfg =>
            {
                cfg.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly());
            });
            return services;
        }
        /// <summary>
        /// AutoMapper
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AutoMapper(this IServiceCollection services)
        {
            return services.AddAutoMapper(typeof(MyAutoMapper));
        }
        /// <summary>
        /// Scoped
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddScoped(this IServiceCollection services)
        {
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            services.AddScoped<JwtTools>();
            return services;
        }
        /// <summary>
        /// 注册JWT
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="builder"></param>
        public static void AddJWT(this IServiceCollection collection,WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {
                // 私钥
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                o.TokenValidationParameters = new TokenValidationParameters()
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = builder.Configuration["Authentication:Audience"],

                    // 验证是否过期
                    ValidateLifetime = true,

                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                };
            });
        }
        /// <summary>
        /// 连接字符串
        /// </summary>
        /// <typeparam name="WorkDbContrxt">EF上下文</typeparam>
        /// <param name="services">扩展的类型</param>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="enableSqlLog">是否打印执行EF语句转义的sql</param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<WorkDbContrxt>(this IServiceCollection services,string? connectionString,bool enableSqlLog) where WorkDbContrxt : DbContext
        {
            return services.AddDbContext<WorkDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(
                            maxRetryCount: 10,
                            maxRetryDelay: TimeSpan.FromSeconds(60),
                            errorNumbersToAdd: null);
                }).EnableSensitiveDataLogging();
                if (enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure
                        .AddFilter((categoty, level) => categoty == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).
                        AddConsole();
                    }));
                }
            });
        }
    }
}
